﻿using SD.Toolkits.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using SD.OpcServer.DataImporter.Models;
using SD.OpcServer.Models.Base;
using SD.OpcServer.Models.Entities;

namespace SD.OpcServer.DataImporter
{
    class Program
    {
        /// <summary>
        /// 数据源路径
        /// </summary>
        private const string DataSourcePath = @"Content\Datas\OpcServer.xls";

        /// <summary>
        /// 程序主入口
        /// </summary>
        static void Main()
        {
            //导入变量
            Console.WriteLine("正在导入变量...");
            ImportVariables();
            Console.WriteLine("导入变量完成！");
            Console.WriteLine("-------------------");

            Console.WriteLine("程序结束！");
            Console.ReadKey();
        }

        /// <summary>
        /// 导入变量
        /// </summary>
        static void ImportVariables()
        {
            VariableModel[] variableModels = ExcelReader.ReadFile<VariableModel>(DataSourcePath, "变量");
            IDictionary<string, Dictionary<string, string>> variableValueDescriptionGroups = ExcelReader.ReadFile<VariableValueDescriptionModel>(DataSourcePath, "变量值描述").GroupBy(x => x.变量编号).ToDictionary(x => x.Key, x => x.ToDictionary(y => y.变量值, y => y.变量值描述));

            using (DbSession dbSession = new DbSession())
            {
                IList<Variable> variables = new List<Variable>();
                foreach (VariableModel variableModel in variableModels)
                {
                    IDictionary<string, string> valueDescriptions = null;
                    if (variableValueDescriptionGroups.ContainsKey(variableModel.变量编号))
                    {
                        valueDescriptions = variableValueDescriptionGroups[variableModel.变量编号];
                    }

                    Variable variable = new Variable(variableModel.变量编号, variableModel.变量名称, variableModel.数据类型, variableModel.单位, variableModel.是否记录历史, variableModel.设备编号, variableModel.描述, valueDescriptions);
                    variables.Add(variable);
                }

                dbSession.Set<Variable>().AddRange(variables);
                dbSession.SaveChanges();
            }
        }
    }
}
